package com.netty.demo.binary.factorial;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.math.BigInteger;

/**
 * @author shengtao
 * @Description:
 * @date 2018/09/10 13:41
 */
public class NumberEncoder extends MessageToByteEncoder<Number> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Number msg, ByteBuf out) throws Exception {
        // Convert to a BigInteger first for easier implementation.
        BigInteger v;
        if(msg instanceof BigInteger){
            v = (BigInteger)msg;
        }else {
            v = new BigInteger(String.valueOf(msg));
        }
        // Convert the number into a byte array.
        byte[] data = v.toByteArray();
        int dataLength = data.length;
        // Write a message.
        out.writeByte((byte) 'F'); // magic number
        out.writeInt(dataLength);  // data length
        out.writeBytes(data);      // data
    }
}
